import 'dart:async';
import 'dart:ui' as ui;

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:top_foundation/top_foundation.dart';
import 'package:whale/helper/utils/img_util.dart';

class ImageGenerator {
  var imgs = [
    'avater.png'.imgPathMe,
  ];
  Future<Uint8List?> generate(String title) async {
    final recorder = ui.PictureRecorder();

    ui.Paint paint = new Paint()
      ..isAntiAlias = true
      ..filterQuality = ui.FilterQuality.high;
    double textMargin = 20.r; // 文字间间距，包括距离矩形边框左右间距
    // 获取标题高度等信息
    double textMaxWidth = 300.r;
    TextPainter titlePainter = TextPainter(
        textScaler: ScreenAdapter().textScale,
        text: TextSpan(
          text: title,
          style: TextStyle(
            fontSize: 30.sp.toInt().toDouble(),
            color: const Color(0xff000000),
          ),
        ),
        textDirection: TextDirection.ltr)
      ..layout(maxWidth: textMaxWidth);
    var titleHeight = titlePainter.height;
    var titleWidth = titlePainter.width;
    print("titleHeight =  $titleHeight");

    double textHeight = (titleHeight + 2 * textMargin);
    double textWidth = (titleWidth + 2 * textMargin);

    // 利用矩形左边的X坐标、矩形顶部的Y坐标、矩形右边的X坐标、矩形底部的Y坐标确定矩形的大小和位置
    var canvasRect = Rect.fromLTWH(0, 0, textWidth + 75.r, textHeight);
    final canvas = Canvas(recorder, canvasRect);
    // 0. 绘制背景
    canvas.drawColor(Colors.transparent, BlendMode.color);

    // 2. 绘制矩形，先绘制矩形，否则文字被覆盖
    paint.color = const Color(0xffE6F9FF);
    var rrect = RRect.fromRectAndRadius(
        Rect.fromLTWH(0, 0, textWidth + 75.r, textHeight),
        Radius.circular(50.r));

    canvas.drawRRect(rrect, paint);

    // double trangleWidth = 40.r;
    // Path path = Path()
    //   ..moveTo(textWidth / 2 - trangleWidth / 2, textHeight + 10.r);
    // path.lineTo(textWidth / 2 + trangleWidth / 2, textHeight + 10.r);
    // path.lineTo(textWidth / 2, textHeight + trangleWidth * 0.8);
    // canvas.drawPath(
    //     path,
    //     paint
    //       ..style = PaintingStyle.fill
    //       ..color = Colors.white);

    // double bottom = textHeight + trangleWidth;
    // print("bottom = $bottom");

    var _img = await generatorImage(size: Size(30, 30));

    canvas.drawImage(_img, ui.Offset.zero, paint);
    // 3. 绘制文字
    titlePainter.paint(canvas, Offset(textMargin + 60.r, textMargin - 3.r));

    // 转换成图片
    final picture = recorder.endRecording();

    ui.Image img = await picture.toImage(
        textWidth.toInt() + (75.r).toInt(), textHeight.toInt());

    print('img的尺寸: $img');
    ByteData? _data = await img.toByteData(format: ui.ImageByteFormat.png);
    var _icondata = _data?.buffer.asUint8List();
    return _icondata;
  }

  Future<ui.Image> generatorImage({required Size size}) async {
    final recorder = ui.PictureRecorder();
    var canvasRect = Rect.fromLTWH(0, 0, size.width, size.height);
    final canvas = Canvas(recorder, canvasRect);
    var _img = await _loadUiImage(imgs[0]);
    ui.Paint imgPaint = Paint()
      ..isAntiAlias = true
      ..filterQuality = FilterQuality.high
      ..color = Colors.red;

    canvas.drawRect(
      Rect.fromLTWH(0, 0, size.width, size.height),
      imgPaint,
    );
    canvas.drawImageRect(
        _img,
        Rect.fromLTWH(0, 0, _img.width.toDouble(), _img.height.toDouble()),
        canvasRect,
        imgPaint);
    // 转换成图片
    final picture = recorder.endRecording();

    ui.Image img =
        await picture.toImage(size.width.toInt(), size.height.toInt());
    return img;
  }
}

Future<ui.Image> _loadUiImage(String imageAssetPath) async {
  final ByteData data = await rootBundle.load(imageAssetPath);
  final Completer<ui.Image> completer = Completer();
  ui.decodeImageFromList(Uint8List.view(data.buffer), (ui.Image img) {
    return completer.complete(img);
  });
  return completer.future;
}
